import { Articles, Channel } from '@/types/data'
import { HomeAction } from '@/types/store'
import sortBy from 'lodash/sortBy'

type HomeState = {
  channels: Channel[]
  restChannels: Channel[]
  channelActionKey: number
  channelArticles: {
    [key in number]?: Articles
  }
}

const InitialState: HomeState = {
  channels: [],
  restChannels: [],
  channelActionKey: 0,
  channelArticles: {},
}

export const home = (state = InitialState, action: HomeAction): HomeState => {
  if (action.type === 'home/getChannels') {
    return {
      ...state,
      channels: action.payload,
    }
  }
  if (action.type === 'home/getRestChannels') {
    return {
      ...state,
      restChannels: action.payload,
    }
  }
  if (action.type === 'home/toggleChannels') {
    return {
      ...state,
      channelActionKey: action.payload,
    }
  }
  if (action.type === 'home/delChannel') {
    return {
      ...state,
      channels: state.channels.filter((item) => item.id !== action.payload.id),
      restChannels: sortBy([...state.restChannels, action.payload], 'id'),
    }
  }
  if (action.type === 'home/addChannel') {
    return {
      ...state,
      channels: [...state.channels, action.payload],
      restChannels: state.restChannels.filter(
        (item) => item.id !== action.payload.id
      ),
    }
  }
  if (action.type === 'home/getArticleListByChannelId') {
    const {
      channelId,
      articles: { pre_timestamp, results },
    } = action.payload

    const currentArticles = state.channelArticles[channelId]?.results ?? []
    return {
      ...state,
      channelArticles: {
        ...state.channelArticles,
        [channelId]: {
          pre_timestamp,
          results: [...currentArticles, ...results],
        },
      },
    }
  }
  if (action.type === 'home/getNewestArticleList') {
    const {
      channelId,
      articles: { pre_timestamp, results },
    } = action.payload

    const currentResults = state.channelArticles[channelId]?.results ?? []
    return {
      ...state,
      channelArticles: {
        ...state.channelArticles,
        [channelId]: {
          pre_timestamp,
          results: [...results, ...currentResults],
        },
      },
    }
  }
  return state
}
